/**
 * 
 * @authors Your Name (you@example.org)
 * @date    2015-12-16 12:57:50
 * @version $Id$
 */
//构造函数
//变量定义var flag=0;
//属性定义this.flag = 0;
function CtrlBar(parent){
	this.larrad = 80;//大圆半径
	this.smlrad = 50;//摇杆半径
	this.max = 10;
	var self = this;
	var flag=0;//拖动标志位（描述是否被拖动）
	this.$canvas = $("<canvas width='200' height='200'></canvas>");
	this.$canvas.attr("class", "directionBtnCanvas");
	parent.append(this.$canvas);
	var canvas=this.$canvas[0];
	if(canvas.getContext)
	{
		var ctx=canvas.getContext('2d');

		this.drawBtn(ctx,100,100);//进入之前先画一个填充圆


		this.$canvas.on('mousedown',function(e){
			os=self.$canvas.offset();
			//console.log(os.left+"+"+os.top);
			var x=e.pageX-os.left;   //鼠标在canvas页面点击的坐标
			var y=e.pageY-os.top;


			var rPow=Math.pow((x-100),2)+Math.pow((y-100),2);
			var r=parseInt(Math.sqrt(rPow));//判断鼠标点击位置离圆心的距离

			if(r<self.larrad)
			{
				flag=1;
				self.$canvas.trigger("beginsw");
			}
		});

		$(window).on('mousemove',function(e){
			e.preventDefault();
			if(flag)
			{

				var x=e.pageX-os.left;   //鼠标在canvas页面点击的坐标
				var y=e.pageY-os.top;
				var mx=x-100;
				var my=y-100;

				//console.log(mx+'#'+my);
				if(Math.abs(mx)<self.larrad && Math.abs(my)<self.larrad)
				{
					self.drawBtn(ctx,100+mx,100+my);
					//ctrlRide(100+mx,100+my);
					self.$canvas.trigger("swing", [mx/self.larrad*self.max,
						my/self.larrad*self.max]);
				}
				else
				{
					var mR=Math.sqrt(Math.pow(mx,2)+Math.pow(my,2));
					mR=parseInt(mR)

					var a=parseInt((mx*self.larrad)/mR);
					var b=parseInt((my*self.larrad)/mR);
					self.drawBtn(ctx,100+a,100+b);
					//ctrlRide(100+a,100+b);
					self.$canvas.trigger("swing", [a/self.larrad*self.max,
						b/self.larrad*self.max]);
				}

			}
		});

		$(window).on('mouseup',function(e){
			e.preventDefault();
			flag=0;
			self.drawBtn(ctx,100,100);
			self.$canvas.trigger("fang",0,0);

		});

		this.reflush = function(){
			self.drawBtn(ctx,100,100);
		}
	}
}

CtrlBar.prototype.setMax = function(maxnum){
	this.max = maxnum;
}

CtrlBar.prototype.bind = function(type, fnt){
	this.$canvas.on(type, fnt);
}

CtrlBar.prototype.setPosition = function(x, y){
	this.$canvas.css({"left":x+"px", "top":y+"px"});
}

CtrlBar.prototype.drawBtn = function (ctx,x,y){
		ctx.beginPath();
		ctx.clearRect(0,0,500,500);
		ctx.fill();
		ctx.closePath();

		ctx.beginPath();
		ctx.lineWidth='2';
		ctx.fillStyle='rgba(150,150,150,0.4)';
		ctx.arc(100,100,this.larrad,0,Math.PI*2,false);
		console.log(this.$canvas.width()/2)
		ctx.fill();
		ctx.closePath();
		ctx.beginPath();
		ctx.fillStyle='rgba(200,0,0,0.8)';
		ctx.arc(x,y,this.smlrad,0,Math.PI*2,false);
		ctx.fill();
		ctx.closePath();

}
